package com.wjy.common.resttemplate;

import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.client.ResponseErrorHandler;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * @author wjy
 * @desc RestTemplate异常处理（调用成功，返回错误）
 * @data 2019年4月24日
 */
@Log4j2
@Component
public class RestExceptionHandle implements ResponseErrorHandler {

    /*
     * 异常是否处理
     */
    @Override
    public boolean hasError(ClientHttpResponse response) throws IOException {
        // if (response.getRawStatusCode() == 200) {
        // return false;
        // } else {
        // return true;
        // }
        return false;
    }

    /*
     * 处理异常
     */
    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
        HttpHeaders httpHeaders = response.getHeaders();
        MediaType mediaType = httpHeaders.getContentType();
        Charset charset = mediaType.getCharset();
        String name = charset.name();
        InputStream inputStream = response.getBody();
        byte[] bs = FileCopyUtils.copyToByteArray(inputStream);
        String body = new String(bs, name);
        log.error(body);
    }

}
